package jdec.jdt.ls.decompiler.cfr;

import static org.eclipse.jdt.ls.core.internal.handlers.MapFlattener.getValue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.benf.cfr.reader.api.CfrDriver;
import org.benf.cfr.reader.api.OutputSinkFactory;
import org.benf.cfr.reader.api.SinkReturns.LineNumberMapping;
import org.benf.cfr.reader.apiunreleased.ClassFileSource2;
import org.benf.cfr.reader.entities.ClassFile;
import org.benf.cfr.reader.entities.Method;
import org.benf.cfr.reader.state.ClassFileSourceImpl;
import org.benf.cfr.reader.state.DCCommonState;
import org.benf.cfr.reader.state.TypeUsageCollectingDumper;
import org.benf.cfr.reader.state.TypeUsageInformation;
import org.benf.cfr.reader.util.CannotLoadClassException;
import org.benf.cfr.reader.util.getopt.Options;
import org.benf.cfr.reader.util.getopt.OptionsImpl;
import org.benf.cfr.reader.util.output.IllegalIdentifierDump;
import org.benf.cfr.reader.util.output.StreamDumper;
import org.benf.cfr.reader.util.output.StringStreamDumper;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.ls.core.internal.JDTUtils;
import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;
import org.eclipse.jdt.ls.core.internal.preferences.Preferences;
import jdec.jdt.ls.decompiler.common.CachingDecompiler;
import jdec.jdt.ls.decompiler.common.JavaDecompilerPlugin;
import jdec.jdt.ls.decompiler.common.SupportDecompilerType;
import jdec.jdt.ls.decompiler.common.util.FileUtil;
import jdec.jdt.ls.decompiler.common.util.JarClassExtractor;

public class CFRDecompiler extends CachingDecompiler {

    public static final String OPTIONS_KEY = "java.decompiler.cfr";
    public static final String DECOMPILED_HEADER = "// Source code was generated by the CFR decompiler. \n";

    Map<String, String> globalOptions = new ConcurrentHashMap<>();

    @Override
    public void setDecompilePreferences(Preferences preferences) {
        Object options = getValue(preferences.asMap(), OPTIONS_KEY);
        if (options instanceof Map) {
            // convert all values to strings
            Map<String, Object> optionsMap = (Map<String, Object>) options;
            for (String key : optionsMap.keySet()) {
                Object value = optionsMap.get(key);
                if (value != null && !(value instanceof String)) {
                    optionsMap.put(key, value.toString());
                }
            }

            this.globalOptions.putAll((Map<String, String>) options);

            // debugger
            this.globalOptions.put(OptionsImpl.TRACK_BYTECODE_LOC.getName(), Boolean.TRUE.toString());
        }
    }

    @Override
    protected String decompileContent(URI uri, IProgressMonitor monitor) throws CoreException {
        IClassFile classFile = JDTUtils.resolveClassFile(uri);
        if (classFile != null) {
            return decompileContent(classFile.getType(), monitor);
        }

        Options options = OptionsImpl.getFactory().create(this.globalOptions);
        return getContent(new ClassFileSourceImpl(options), uri.getPath(), options, monitor);
    }

    @Override
    protected String decompileContent(IType type, IProgressMonitor monitor) throws CoreException {
        Options options = OptionsImpl.getFactory().create(this.globalOptions);
        // return getContent(new JDTClassFileSource(classFile, options),
        // JDTClassFileSource.FAKE_PATH, options, monitor);
        return getContent2(new JDTClassFileSource(type, options), JDTClassFileSource.FAKE_PATH, monitor);
    }

    /**
     * CFR反编译
     * 
     * @param classFileSource
     * @param path
     * @param monitor
     * @return
     */
    private String getContent2(ClassFileSource2 classFileSource, String path, IProgressMonitor monitor) {
        final StringBuilder sbr = new StringBuilder(8192);
        final NavigableMap<Integer, Integer> lineMapping = new TreeMap<>();

        OutputSinkFactory mySink = new OutputSinkFactory() {
            @Override
            public List<SinkClass> getSupportedSinks(SinkType sinkType, Collection<SinkClass> collection) {
                return Arrays.asList(SinkClass.STRING, SinkClass.DECOMPILED, SinkClass.DECOMPILED_MULTIVER, SinkClass.EXCEPTION_MESSAGE,
                        SinkClass.LINE_NUMBER_MAPPING);
            }

            @Override
            public <T> Sink<T> getSink(final SinkType sinkType, final SinkClass sinkClass) {
                return new Sink<>() {
                    @Override
                    public void write(T sinkable) {
                        // skip message like: Analysing type demo.MathGame
                        if (sinkType == SinkType.PROGRESS) {
                            return;
                        }
                        if (sinkType == SinkType.LINENUMBER) {
                            LineNumberMapping mapping = (LineNumberMapping) sinkable;
                            NavigableMap<Integer, Integer> classFileMappings = mapping.getClassFileMappings();
                            NavigableMap<Integer, Integer> mappings = mapping.getMappings();
                            if (classFileMappings != null && mappings != null) {
                                for (Entry<Integer, Integer> entry : mappings.entrySet()) {
                                    Integer srcLineNumber = classFileMappings.get(entry.getKey());
                                    lineMapping.put(entry.getValue(), srcLineNumber);
                                }
                            }
                            return;
                        }
                        sbr.append(sinkable);
                    }
                };
            }
        };

        CfrDriver driver =
                new CfrDriver.Builder().withClassFileSource(classFileSource).withOptions(this.globalOptions).withOutputSink(mySink).build();
        List<String> toAnalyse = new ArrayList<>();
        toAnalyse.add(path);
        driver.analyse(toAnalyse);

        String resultCode = sbr.toString();
        if (!lineMapping.isEmpty()) {
            resultCode = addLineNumber(resultCode, lineMapping);
        }
        return resultCode;
    }


    /**
     * inner learn
     * 
     * @param classFileSource
     * @param path
     * @param options
     * @param monitor
     * @return
     * @throws CoreException
     */
    @Deprecated
    private String getContent(ClassFileSource2 classFileSource, String path, Options options, IProgressMonitor monitor) throws CoreException {
        try {
            DCCommonState commonState = new DCCommonState(options, classFileSource);
            ClassFile classFile = commonState.getClassFileMaybePath(path);
            commonState.configureWith(classFile);

            try {
                classFile = commonState.getClassFile(classFile.getClassType());
            } catch (CannotLoadClassException e) {
                // ignore
            }
            if (options.getOption(OptionsImpl.DECOMPILE_INNER_CLASSES).booleanValue()) {
                classFile.loadInnerClasses(commonState);
            }

            TypeUsageCollectingDumper collectingDumper = new TypeUsageCollectingDumper(options, classFile);
            classFile.analyseTop(commonState, collectingDumper);

            TypeUsageInformation typeUsageInformation = collectingDumper.getRealTypeUsageInformation();

            IllegalIdentifierDump illegalIdentifierDump = IllegalIdentifierDump.Factory.get(options);

            final StringBuilder source = new StringBuilder();
            StreamDumper dumper = new StringStreamDumper((Method method, String s) -> {
                JavaLanguageServerPlugin.logInfo("Error decompiling method " + method.getName() + ": " + s);
            }, source, typeUsageInformation, options, illegalIdentifierDump);
            // dumper = dumperFactory.wrapLineNoDumper(dumper);

            classFile.dump(dumper);

            String code = DECOMPILED_HEADER + source.toString();
            // return new EclipseFormater().formatSource(code);
            return code;
        } catch (Throwable t) {
            throw new CoreException(new Status(IStatus.ERROR, "jdec.jdt.ls.decompiler.cfr", "Error decompiling", t));
        }
    }

    @Override
    public String decompileFromArchive(String archivePath, String packege, String className, IProgressMonitor monitor) throws CoreException {
        File workingDir = new File(JavaDecompilerPlugin.tempDir());

        try {
            workingDir.mkdirs();
            JarClassExtractor.extract(archivePath, packege, className, true, workingDir.getAbsolutePath());

            Path path = Paths.get(workingDir.getAbsolutePath()).resolve(className);

            return decompileContent(path.toUri(), monitor);
        } catch (Exception e) {
            throw new CoreException(new Status(IStatus.ERROR, "java.decompiler.cfr", "Error decompiling", e));
        } finally {
            FileUtil.deltree(workingDir);
        }
    }

    @Override
    protected String getDecompilerType() {
        return SupportDecompilerType.CFR;
    }


    private String addLineNumber(String src, Map<Integer, Integer> lineMapping) {
        int maxLineNumber = 0;
        for (Integer value : lineMapping.values()) {
            if (value != null && value > maxLineNumber) {
                maxLineNumber = value;
            }
        }

        String formatStr = "/*%2d*/ ";
        String emptyStr = "       ";

        StringBuilder sb = new StringBuilder();

        List<String> lines = toLines(src);

        if (maxLineNumber >= 100) {
            formatStr = "/*%3d*/ ";
            emptyStr = "        ";
        } else if (maxLineNumber >= 1000) {
            formatStr = "/*%4d*/ ";
            emptyStr = "         ";
        }

        int index = 0;
        for (String line : lines) {
            Integer srcLineNumber = lineMapping.get(index + 1);
            if (srcLineNumber != null) {
                sb.append(String.format(formatStr, srcLineNumber));
            } else {
                sb.append(emptyStr);
            }
            sb.append(line).append("\n");
            index++;
        }

        return sb.toString();
    }

    List<String> toLines(String text) {
        List<String> result = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new StringReader(text));) {
            String line = reader.readLine();
            while (line != null) {
                result.add(line);
                line = reader.readLine();
            }
        } catch (IOException exc) {
            // quit
        }
        return result;
    }
}
